package com.example.chessbattleplatform.web.chess_rooms.controller;

import com.example.chessbattleplatform.Pojo.Result.WebResult;
import com.example.chessbattleplatform.utils.JsonFileUtils;
import com.example.chessbattleplatform.utils.ThreadJwtParseUtils;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.Vo.UpdateRoomVo;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.dto.RoomsDto;
import com.example.chessbattleplatform.web.chess_rooms.service.impl.RoomsServiceInterface;
import com.example.chessbattleplatform.web.chess_rooms.websocket.RoomsMemberWebSocketServer;
import com.example.chessbattleplatform.web.chess_rooms.websocket.RoomsWebSocketServer;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/chess-rooms")
@RequiredArgsConstructor
public class RoomsController {

    private final RoomsServiceInterface roomsServiceInterface;
    private final ThreadJwtParseUtils threadJwtParseUtils;

    /**
     * 创建房间
     */
    @PostMapping("/rooms")
    public WebResult<UpdateRoomVo> CreateNewRoom(@Valid @RequestBody RoomsDto roomsDto) {
        JsonFileUtils.saveJsonToFile("创建房间", roomsDto);
        // 获取 用户 信息
        Long threadUserId = threadJwtParseUtils.getThreadUserId();

        UpdateRoomVo room = roomsServiceInterface.createRoom(roomsDto, threadUserId);

        // webSocket 更新数据
        RoomsWebSocketServer.sendListQueriesMessage();

        return WebResult.success(room);
    }

    /***
     * 修改房间
     */
    @PutMapping("/rooms")
    public WebResult<?> UpdateRoom(@Valid @RequestBody RoomsDto roomsDto) {
        log.info("接收的数据{}", roomsDto);


        // webSocket 更新数据
        RoomsWebSocketServer.sendListQueriesMessage();
        // 更新所有用户房间信息
        RoomsMemberWebSocketServer.sendQueriesMessages();

        return null;
    }

    /**
     * 删除等待房间
     */
    @DeleteMapping("/rooms")
    public WebResult<UpdateRoomVo> deleteTheWaitingRoom(@NotNull(message = "删除等待房间号，不能为空") String roomId) {
        // 获取 用户 信息
        Long threadUserId = threadJwtParseUtils.getThreadUserId();
        UpdateRoomVo updateRoomVo = roomsServiceInterface.deleteTheWaitingRoomData(roomId, threadUserId);
        // webSocket 更新数据
        RoomsWebSocketServer.sendListQueriesMessage();
        // 更新所有用户房间信息
        RoomsMemberWebSocketServer.sendQueriesMessages();
        return WebResult.success(updateRoomVo);

    }


}
